const express = require('express');
const router = express.Router();
const Menu = require('../models/menu');

// 统一的响应格式
const createResponse = (code = 0, message = 'success', data = null) => ({
    code,
    success: code === 0,
    message,
    data
});

/**
 * @api {get} /menus 获取菜单列表
 */
router.get('/', async (req, res) => {
    try {
        const menus = await Menu.find({ isShow: true }).sort({ sort: 1 });
        const menuTree = buildMenuTree(menus);
        res.json(createResponse(0, '获取成功', menuTree));
    } catch (err) {
        console.error('获取菜单错误:', err);
        res.json(createResponse(-1, `获取菜单失败: ${err.message}`));
    }
});

/**
 * @api {post} /menus/add 创建菜单
 */
router.post('/add', async (req, res) => {
    try {
        const { name, path, icon, sort, parentId } = req.body;

        const newMenu = await Menu.create({
            name,
            path,
            icon,
            sort: sort || 0,
            parentId: parentId || null
        });

        res.json(createResponse(0, '创建成功', newMenu));
    } catch (err) {
        console.error('创建菜单错误:', err);
        res.json(createResponse(-1, `创建菜单失败: ${err.message}`));
    }
});

/**
 * @api {post} /menus/update 更新菜单
 */
router.post('/update', async (req, res) => {
    try {
        const { id, ...updateData } = req.body;
        updateData.updateTime = new Date();

        const menu = await Menu.findByIdAndUpdate(
            id,
            updateData,
            { new: true }
        );

        if (!menu) {
            return res.json(createResponse(-1, '菜单不存在'));
        }

        res.json(createResponse(0, '更新成功', menu));
    } catch (err) {
        console.error('更新菜单错误:', err);
        res.json(createResponse(-1, `更新菜单失败: ${err.message}`));
    }
});

/**
 * @api {post} /menus/delete 删除菜单
 */
router.post('/delete', async (req, res) => {
    try {
        const { id } = req.body;
        
        // 检查是否有子菜单
        const hasChildren = await Menu.exists({ parentId: id });
        if (hasChildren) {
            return res.json(createResponse(-1, '请先删除子菜单'));
        }

        const menu = await Menu.findByIdAndDelete(id);
        if (!menu) {
            return res.json(createResponse(-1, '菜单不存在'));
        }

        res.json(createResponse(0, '删除成功'));
    } catch (err) {
        console.error('删除菜单错误:', err);
        res.json(createResponse(-1, `删除菜单失败: ${err.message}`));
    }
});

/**
 * @api {post} /menus/toggle 切换菜单显示状态
 */
router.post('/toggle', async (req, res) => {
    try {
        const { id } = req.body;
        
        const menu = await Menu.findById(id);
        if (!menu) {
            return res.json(createResponse(-1, '菜单不存在'));
        }

        menu.isShow = !menu.isShow;
        menu.updateTime = new Date();
        await menu.save();

        res.json(createResponse(0, menu.isShow ? '显示成功' : '隐藏成功', menu));
    } catch (err) {
        console.error('切换菜单状态错误:', err);
        res.json(createResponse(-1, `操作失败: ${err.message}`));
    }
});

// 构建树形菜单的辅助函数
function buildMenuTree(menus, parentId = null) {
    return menus
        .filter(menu => String(menu.parentId) === String(parentId))
        .map(menu => ({
            ...menu.toObject(),
            children: buildMenuTree(menus, menu._id)
        }))
        .sort((a, b) => a.sort - b.sort);
}

module.exports = router; 